package educationaladministrationsystem.Interceptor;

import com.alibaba.fastjson.JSONObject;
import educationaladministrationsystem.Result.Result;
import educationaladministrationsystem.Tool.JWTUnits;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

@Component
@Slf4j
public class LoginCheckInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("tokenCertification");       // 截去开头的Bearer
        log.info(token);
//        token没有内容的情况
        if (!StringUtils.hasLength(token)) {
            response.getWriter().write(JSONObject.toJSONString(Result.error("NOT LOGIN")));
            return false;
        }
        try {
            JWTUnits.parseJWT(token);
        } catch (Exception e) {
            response.getWriter().write(JSONObject.toJSONString(Result.error("TOKEN FAULT")));
            return false;
        }
        return true;
    }
}
